package service

import (
	"context"
	"encoding/json"
	"time"
	"video-srv/basic/config"

	__ "video-srv/basic/proto"
	"video-srv/handler/model"
)

type Server struct {
	__.UnimplementedVideoServer
}

func (s *Server) AddVideo(_ context.Context, in *__.AddVideoReq) (*__.AddVideoResp, error) {

	var video model.Video

	video = model.Video{
		Title:    in.Title,
		Category: in.TypeId,
		Tags:     in.Tag,
		CoverUrl: in.Image,
		VideoUrl: in.VideoUrl,
	}

	err := video.AddVideo()
	if err != nil {
		return nil, err
	}

	return &__.AddVideoResp{VideoId: int64(video.Id)}, nil
}

func (s *Server) UpdateStatusVideo(_ context.Context, in *__.UpdateStatusVideoReq) (*__.UpdateStatusVideoResp, error) {

	return &__.UpdateStatusVideoResp{}, nil
}

func (s *Server) GetKeyVideo(_ context.Context, in *__.GetKeyVideoReq) (*__.GetKeyVideoResp, error) {

	var video model.Video

	var list []*__.GetKeyVideo

	videoList, err := video.FindVideoList()
	if err != nil {
		return nil, err
	}

	for _, v := range videoList {
		vale := &__.GetKeyVideo{
			VideoId:  int64(v.Id),
			Title:    v.Title,
			Category: v.Category,
			Tags:     v.Tags,
			CoverUrl: v.CoverUrl,
			VideoUrl: v.VideoUrl,
			Status:   int64(v.Status),
		}

		list = append(list, vale)
	}

	marshal, err := json.Marshal(list)
	if err != nil {
		return nil, err
	}

	config.RDB.Set(config.Ctx, "videoList", marshal, time.Hour)

	return &__.GetKeyVideoResp{List: list}, nil
}
